package com.bryant.demo05.ui.me

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.bryant.demo05.R
import com.bryant.demo05.WeatherApplication
import com.bryant.demo05.base.BaseBindingFragment
import com.bryant.demo05.databinding.FragmentMeBinding
import com.bryant.demo05.storage.TokenPreferences
import com.bryant.demo05.ui.login.LoginActivity
import com.bryant.demo05.utils.RetrofitClient
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


class MeFragment : BaseBindingFragment<FragmentMeBinding>() {

    // 主要是将xml文件转换成view视图
    override fun initBinding(inflater: LayoutInflater, parent: ViewGroup?): FragmentMeBinding {
        return FragmentMeBinding.inflate(inflater, parent, false)
    }

    // 生命周期函数 - 表示视图初始化
    override fun initView() {
        // 退出登录
        logOut()

        // 实现点击头像跳转
        goToChangeAvatar()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getUserinfo()
    }

    /**
     * 当Fragment重新恢复时调用
     *
     * 在Fragment生命周期中，每次Fragment从不可见到可见状态时都会调用此方法，
     * 此时会重新获取用户信息并更新界面显示
     */
    override fun onResume() {
        super.onResume()
        getUserinfo()
    }

    // 获取用户信息事件
    private fun getUserinfo() {
        // 请求用户信息 - 协程
        lifecycleScope.launch(Dispatchers.Main) {
            // 转换至IO线程， 发送请求， 获取结果
            val res = withContext(Dispatchers.IO) {
                RetrofitClient.apiService.getUserInfoApi()
            }
            // 判断返回码
            if (res.code == 10000) {
                Toast.makeText(requireContext(), "获取用户信息成功", Toast.LENGTH_SHORT).show()
                val resData = res.data
                // 将用户信息存储到全局中 - 先判断数据不为空
                if (resData != null) {
                    WeatherApplication.getInstance().initUserData(resData)

                }
                binding.tvSignature.text = resData?.motto ?: ""
                binding.tvAccount.text = resData?.username ?: ""
                binding.tvNickname.text = resData?.nick_name ?: ""
                binding.tvGender.text = resData?.gender ?: ""
                loadAvatar(resData?.avatar ?: "")
            } else {
                Toast.makeText(requireContext(), res.message, Toast.LENGTH_SHORT).show()
            }
        }
    }

    // 加载头像（头像是网络图片）
    private fun loadAvatar(url: String) {
        lifecycleScope.launch {
            Glide.with(this@MeFragment)
                .load(url)
                .apply(
                    RequestOptions()
                        .circleCrop()
                        .placeholder(R.mipmap.avatar1)
                        .error(R.mipmap.avatar1)
                )
                // 绑定图片
                .into(binding.ivAvatar)
        }
    }

    // 退出登录方法
    private fun logOut() {
        binding.btnLogout.setOnClickListener {
            // 清除token， 跳转至登录页
            TokenPreferences.getInstance(requireContext()).deleteToken()
            // 跳转至登录页
            startActivity(Intent(requireContext(), LoginActivity::class.java))
        }
    }

    // 修改头像事件
    private fun goToChangeAvatar() {
        binding.ivAvatar.setOnClickListener {
            // 跳转至修改头像页面
            startActivity(Intent(requireContext(), ChangeAvatarActivity::class.java))
        }
        binding.ivEditAvatar.setOnClickListener() {
            // 跳转至修改头像页面
            startActivity(Intent(requireContext(), ChangeAvatarActivity::class.java))
        }
    }
}